package com.ktgj.flight.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.utils.StringUtils;
import com.ktgj.common.core.utils.poi.ExcelUtil;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.core.web.page.TableDataInfo;
import com.ktgj.common.log.annotation.Log;
import com.ktgj.common.log.enums.BusinessType;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.common.security.annotation.PreAuthorize;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.BankCard;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.customer.api.domain.Employee;
import com.ktgj.flight.common.linkstar.domain.CalculateRefundRes;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.AirReIssuePriceRequest;
import com.ktgj.flight.common.linkstar.domain.airReIssuePrice.ReIssuePriceResponse;
import com.ktgj.flight.common.linkstar.domain.changeFlight.ChangeFlightRequest;
import com.ktgj.flight.common.linkstar.domain.fightdetails.FlightInfoReqVo;
import com.ktgj.flight.common.linkstar.domain.fightdetails.FlightInfoVo;
import com.ktgj.flight.common.linkstar.domain.publishprice.FlightPublishPriceReqVo;
import com.ktgj.flight.common.linkstar.domain.publishprice.FlightPublishPriceResVo;
import com.ktgj.flight.common.linkstar.domain.searchFlight.one.FlightTransfer;
import com.ktgj.flight.common.linkstar.domain.stopfight.FightStopReqVo;
import com.ktgj.flight.common.linkstar.domain.stopfight.FightStopResVo;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.InterfaceEntity.*;
import com.ktgj.flight.domain.vo.*;
import com.ktgj.flight.service.IFlightOrderInfoService;
import com.ktgj.flight.service.IFlightService;
import com.ktgj.flight.vo.FlightResponseVo;
import com.ktgj.flight.vo.FlightVo;
import com.ktgj.pay.api.domain.BankCardApi;
import com.ktgj.pay.api.domain.CustomerApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

;

/**
 * 航线信息维护Controller
 *
 * @author ruoyi
 * @date 2021-08-30
 */
@ControllerAdvice
@RestController
@RequestMapping("/flight")
public class FlightController extends BaseController {

    @Autowired
    private IFlightService flightService;

    @Autowired
    private IFlightOrderInfoService orderInfoService;

    @Autowired
    private RemoteCustomerService customerService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    /**
     * 查询航线信息维护列表
     */
    @PreAuthorize(hasPermi = "flight:flight:list")
    @GetMapping("/list")
    public TableDataInfo list(Flight flight) {
        startPage();
        List<Flight> list = flightService.selectFlightList(flight);
        return getDataTable(list);
    }

    /**
     * 根据查询条件查询航班信息(航班查询)
     *
     * @param
     */
    @PostMapping("/getFlightInfoList")
    public AjaxResult getFlightInfoListBySearchCondition(HttpServletRequest request, @RequestBody MoFlightSearchRequest searchRequest) {
        try {
            String token = request.getHeader("token");
            List<FlightResponseVo> flightList = null;
            if (token != null && !token.equals("")) {
                R<Customer> customer = customerService.getLoginCustomerByToken(token);
                flightList = flightService.getFlightInfoListBySearchCondition(customer.getData(), searchRequest);
            } else {
                flightList = flightService.getFlightInfoListBySearchCondition(null, searchRequest);
            }

            return AjaxResult.success(flightList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 小程序查询往返航班去程列表
     *
     * @param
     */
    @PostMapping("/flightInfoList")
    public AjaxResult getFlightInfoList(HttpServletRequest request, @RequestBody MoFlightSearchRequest searchRequest) {
        try {
            List<FlightVo> flightInfoList = null;
            String token = request.getHeader("token");
            if (token != null) {
                R<Customer> customer = customerService.getLoginCustomerByToken(token);
                flightInfoList = flightService.getFlightInfoList(customer.getData(), searchRequest);
            } else {
                flightInfoList = flightService.getFlightInfoList(null, searchRequest);
            }
            return AjaxResult.success(flightInfoList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 小程序查询往返航班返程列表
     *
     * @param
     */
    @PostMapping("/getFlightInfoListBack")
    public AjaxResult getFlightInfoListBack(HttpServletRequest request, @RequestBody MoFlightSearchRequest searchRequest) {
        try {
            List<FlightVo> flightInfoList = null;
            String token = request.getHeader("token");
            if (token != null) {
                R<Customer> customer = customerService.getLoginCustomerByToken(token);
                flightInfoList = flightService.getFlightInfoListBack(customer.getData(), searchRequest);
            } else {
                flightInfoList = flightService.getFlightInfoListBack(null, searchRequest);
            }
            if (flightInfoList != null && flightInfoList.size() > 0)
                return AjaxResult.success(flightInfoList);
            else
                return AjaxResult.error("航班信息发生变化，请重新查询！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 航班详情（单程）
     * @param searchRequest
     * @return
     */
    @PostMapping("/flightDetails")
    public AjaxResult flightDetails(HttpServletRequest request, @RequestBody MoFlightSearchRequest searchRequest) {
        try {
            String token = request.getHeader("token");
            FlightVo flightVo = null;
            if (token != null && !token.equals("")) {
                R<Customer> customer = customerService.getLoginCustomerByToken(token);
                flightVo = flightService.flightDetails(customer.getData(), searchRequest);
            } else {
                flightVo = flightService.flightDetails(null, searchRequest);
            }
            return AjaxResult.success(flightVo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 航班详情（中转）
     * @param map
     * @return
     */
    @PostMapping("/flightTransfers")
    public AjaxResult flightTransfers(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        try {
            String token = request.getHeader("token");
            FlightTransfer transfers = null;
            String transferId = String.valueOf(map.get("transferId"));
            String depDate = String.valueOf(map.get("depDate"));
            String dstAirport = String.valueOf(map.get("dstAirport"));
            String orgAirport = String.valueOf(map.get("orgAirport"));
            if (token != null && !token.equals("")) {
                R<Customer> customer = customerService.getLoginCustomerByToken(token);
                transfers = flightService.flightTransfers(customer.getData(), transferId, depDate, dstAirport, orgAirport);
            } else {
                transfers = flightService.flightTransfers(null, transferId, depDate, dstAirport, orgAirport);
            }

            return AjaxResult.success(transfers);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 航班详情（往返）
     * @param searchRequest
     * @return
     */
    @PostMapping("/flightReturn")
    public AjaxResult flightReturn(HttpServletRequest request, @RequestBody MoFlightSearchRequest searchRequest) {
        try {
            String token = request.getHeader("token");
            FlightResponseDTO responseDTO = null;
            if (token != null && !token.equals("")) {
                R<Customer> customer = customerService.getLoginCustomerByToken(token);
                responseDTO = flightService.flightReturn(customer.getData(), searchRequest);
            } else {
                responseDTO = flightService.flightReturn(null, searchRequest);
            }
            return AjaxResult.success(responseDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 根据查询条件查询航班信息(航班查询)
     *
     * @param
     */
    @PostMapping("/getFlightInfoLists")
    public List<FlightResponseVo> getFlightInfoListBySearchConditions(HttpServletRequest request, @RequestBody MoFlightSearchRequest searchRequest) {
        String token = request.getHeader("token");
        R<Customer> customer;
        try {
            customer = customerService.getLoginCustomerByToken(token);
            List<FlightResponseVo> flightList = flightService.getFlightInfoListBySearchCondition(customer.getData(), searchRequest);
            return flightList;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 航班详细仓位信息查询（领达，航班搜索后，点击某一个航班则展示该航班的详细仓位以及价格）
     * @param vo
     * @return
     */
    @PostMapping("/publishPrice")
    public AjaxResult publishPrice(@RequestBody FlightPublishPriceReqVo vo){
        FlightPublishPriceResVo resVo = flightService.publishPrice(vo);
        if(resVo!=null){
            return AjaxResult.success(resVo);
        }else{
            return AjaxResult.error(resVo.msg);
        }
    }

    /**
     * 根据航班号和日期查询航班信息
     *
     * @param vo
     * @return
     */
    @PostMapping("/getFightInfoByAirCodeAndDate")
    public FightStopResVo getFightInfoByAirCodeAndDate(@RequestBody FightStopReqVo vo) {

        FightStopResVo flightInfoVo = flightService.searchStopFightInfo(vo);
        return flightInfoVo;

    }



    /**
     * 机票下单
     *
     * @param moRequest
     */
    @PostMapping("/createFlightOrder")
    public AjaxResult createFlightOrder(@RequestBody MoCreateOrderRequest moRequest, HttpServletRequest request) {
        String token = request.getHeader("token");

        FlightOrderResponse response = flightService.createOrder(moRequest, token);
        if (!response.isHasSuccess()) {
            return AjaxResult.error(response.getMsg());
        }
        return AjaxResult.success(response);
    }

    /**
     * 生成预定命令（PNR）
     * @param moRequest
     * @return
     */
    @PostMapping("/createPNR")
    public AjaxResult createPNR(@RequestBody MoCreateOrderRequest moRequest) {
        FlightOrderResponse response = flightService.createPNR(moRequest);
        if (!response.isHasSuccess()) {
            return AjaxResult.error(response.getMsg());
        }
        return AjaxResult.success(response);
    }

    @PostMapping("/cancelPNR")
    public AjaxResult cancelPNR(@RequestBody Map<String, String> map)
    {
        String pnr = map.get("pnr");
        return AjaxResult.success(flightService.cancelPNR(pnr));
    }

    /**
     * 保存机票订单（CRM）
     * @param moRequest
     * @return
     */
    @PostMapping("/createOrderCRM")
    public AjaxResult createOrderCRM(@RequestBody MoCreateOrderRequest moRequest) {
        FlightOrderResponse response = flightService.createOrderCRM(moRequest, moRequest.customerId);
        if (!response.isHasSuccess()) {
            return AjaxResult.error(response.getMsg());
        }
        return AjaxResult.success(response);
    }

    /**
     * 查询订单信息
     * @param orderRequest
     * @return
     */
    @PostMapping("/searchFlightOrderInfo")
    public AjaxResult searchFlightOrderInfo(@RequestBody MoQueryOrderRequest orderRequest) {
        MoQueryOrderResponse orderResponse = flightService.searchOrderInfo(orderRequest);
        return AjaxResult.success(orderResponse);
    }

    /**
     * 取消订单
     *
     * @return
     */
    @PostMapping("/cancelFlightOrder")
    public AjaxResult cancelFlightOrder(@RequestBody MoCancelOrderRequest moRequest) {
        MoCancelOrderResponse response = flightService.cancelOrder(moRequest);
        return AjaxResult.success(response);
    }

    /**
     * 支付机票订单
     * @param moRequest
     * @return
     */
    @PostMapping("/payOrder")
    public AjaxResult payOrder(HttpServletRequest request, @RequestBody MoOrderPayRequest moRequest) {
        String token = request.getHeader("token");
        if (token != null && !token.equals("")) {
            R<Employee> employeeByToken;
            try {
                employeeByToken = remoteCustomerService.getLoginEmployeeByToken(token);
                if (employeeByToken.getCode() == 200 && employeeByToken.getData() != null)
                    moRequest.employee = employeeByToken.getData();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }
        } else {
            moRequest.employee = null;
        }
        try {
            MoOrderPayResponse response = flightService.payOrder(moRequest);
            return AjaxResult.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 退票前信息确认(领达)
     * @param refundConfirm 票号
     * @return 返回 退票手续费以及给用户需要退多少钱
     */
    @PostMapping("/orderRefundConfirm")
    public AjaxResult orderRefundConfirm(@RequestBody OrderRefundConfirm refundConfirm){
        CalculateRefundRes refundRes= flightService.orderRefundConfirm(refundConfirm.getTicketNo(), refundConfirm.voluntary());
        if(!refundRes.isSuccess()){
            return AjaxResult.error(refundRes.getMsg());
        }else{
            return AjaxResult.success(refundRes);
        }
    }

    /**
     * 退票
     *
     * @param
     * @return
     */
    @PostMapping("/orderRefund")
    public AjaxResult orderRefund(HttpServletRequest request, @RequestBody MoOrderRefundRequest moRequest) {
        MoOrderRefundResponse response;
        try {
            response = flightService.orderRefund(moRequest, request);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(response);
    }

    /**
     * 退票（CRM）
     * @param orderChange
     * @return
     */
    @PostMapping("/orderRefundCRM")
    public AjaxResult orderRefundCRM(@RequestBody FlightOrderChange orderChange) {
        MoOrderRefundResponse response;
        try {
            response = flightService.orderRefundCRM(orderChange);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(response);
    }

    /**
     * 改签退票
     * @param moRequest
     * @return
     */
    @PostMapping("/changeOrderRefund")
    public AjaxResult changeOrderRefund(HttpServletRequest request, @RequestBody MoOrderRefundRequest moRequest) {
        MoOrderRefundResponse response;
        try {
            response = flightService.changeOrderRefund(moRequest, request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(response);
    }

    /**
     * CRM改签退票
     * @param orderChange
     * @return
     */
    @PostMapping("/changeOrderRefundCRM")
    public AjaxResult changeOrderRefundCRM(@RequestBody FlightOrderChange orderChange) {
        MoOrderRefundResponse response = flightService.changeOrderRefundCRM(orderChange);
        return AjaxResult.success(response);
    }

    /**
     * 导出航线信息维护列表
     */
    @PreAuthorize(hasPermi = "flight:flight:export")
    @Log(title = "航线信息维护", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Flight flight) throws IOException {
        List<Flight> list = flightService.selectFlightList(flight);
        ExcelUtil<Flight> util = new ExcelUtil<Flight>(Flight.class);
        util.exportExcel(response, list, "航线信息维护数据");
    }

    /**
     * 获取航线信息维护详细信息
     */
    @PreAuthorize(hasPermi = "flight:flight:query")
    @GetMapping(value = "/{flightId}")
    public AjaxResult getInfo(@PathVariable("flightId") Long flightId) {
        return AjaxResult.success(flightService.selectFlightById(flightId));
    }

    /**
     * 新增航线信息维护
     */
    @PreAuthorize(hasPermi = "flight:flight:add")
    @Log(title = "航线信息维护", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Flight flight) {
        return toAjax(flightService.insertFlight(flight));
    }

    /**
     * 修改航线信息维护
     */
    @PreAuthorize(hasPermi = "flight:flight:edit")
    @Log(title = "航线信息维护", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Flight flight) {
        return toAjax(flightService.updateFlight(flight));
    }

    /**
     * 删除航线信息维护
     */
    @PreAuthorize(hasPermi = "flight:flight:remove")
    @Log(title = "航线信息维护", businessType = BusinessType.DELETE)
    @DeleteMapping("/{flightIds}")
    public AjaxResult remove(@PathVariable Long[] flightIds) {
        return toAjax(flightService.deleteFlightByIds(flightIds));
    }


    /**
     * 客票变更搜索(改签航班查询)
     * @param request
     * @return
     */
    @PostMapping("/changeSearchFlight")
    public AjaxResult changeSearchFlight(@RequestBody ChangeFlightRequest request){
        try {
            List<FlightVo> flightVos = flightService.changeSearchFlight(request);
            return AjaxResult.success(flightVos);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 改签生成订单
     * @param order
     * @return
     */
    @PostMapping("/changeCreateOrder")
    public AjaxResult changeCreateOrder(@RequestBody ChangeCreateOrder order) {
        FlightOrderResponse response = flightService.changeCreateOrder(order);
        if (response != null)
            return AjaxResult.success(response);
        else
            return AjaxResult.error("系统异常");
    }

    /**
     * 取消改签
     * @param flightCancelChange
     * @return
     */
    @PostMapping("/cancelChange")
    public AjaxResult cancelChange(@RequestBody FlightCancelChangeVO flightCancelChange) {
        if (StringUtils.isEmpty(flightCancelChange.getOrderId()))
            return AjaxResult.error("订单号不能为空！");
        if (flightCancelChange.getTicketNo() == null && flightCancelChange.getTicketNo().size() == 0)
            return AjaxResult.error("票号不能为空！");
        int cancelChange = flightService.cancelChange(flightCancelChange);
        return toAjax(cancelChange);
    }

    /**
     * 计算改签费用（领达使用）
     * @param reIssuePriceRequest
     */
    @PostMapping(value = "/AirReIssuePrice")
    public AjaxResult testAirReIssuePrice(@RequestBody  AirReIssuePriceRequest reIssuePriceRequest){
        ReIssuePriceResponse response = flightService.testAirReIssuePrice(reIssuePriceRequest);
        if(!response.isSuccess()){
            return AjaxResult.error(response.getMsg());
        }else{
            return AjaxResult.success(response);
        }
    }

    /**
     * 客票变更搜索（改签航班详情）
     * @param request
     * @return
     */
    @PostMapping("/changeDetails")
    public AjaxResult changeDetails(@RequestBody ChangeFlightRequest request) {
        FlightVo flightVo = flightService.changeDetails(request);
        if (flightVo != null)
            return AjaxResult.success(flightVo);
        else
            return AjaxResult.error("查询失败!");
    }

    /**
     * 改签机票
     * @param changeRequest
     * @return
     */
    @PostMapping("/ticketChangeFlight")
    public AjaxResult ticketChangeFlight(@RequestBody  MoOrderChangeRequest changeRequest){
        MoOrderChangeResponse response = flightService.ticketChangeFlight(changeRequest);
        if(!response.IsSuccess){
            return AjaxResult.error();
        }
        return AjaxResult.success(response);
    }

    /**
     * 机票查询常用旅客
     * */
    @PostMapping("/fileCommonTravelers")
    public AjaxResult fileCommonTravelers(HttpServletRequest request){
        String token = request.getHeader("token");
        FileCommonTravelersVo fileCommonTravelersVo;
        try {
            fileCommonTravelersVo = flightService.fileCommonTravelers(token);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        if (fileCommonTravelersVo != null && fileCommonTravelersVo.getLetterList().size() > 0){
            return AjaxResult.success(fileCommonTravelersVo);
        }
        else {
            return AjaxResult.error("未查到信息");
        }
    }

    /**
     * 机票查询常用旅客（CRM）
     * */
    @PostMapping("/bankCommonTravelers")
    public AjaxResult bankCommonTravelers(@RequestBody Map<String, Object> map){
        if (map.get("customerId") != null && !map.get("customerId").equals("")){
            List<FileCommonTravelers> travelersList;
            try {
                travelersList = flightService.bankCommonTravelers(map);
            } catch (Exception e){
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }
            if (travelersList != null && travelersList.size() > 0){
                return AjaxResult.success(travelersList);
            }
            else {
                return AjaxResult.error("未查到信息");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 机票银行卡支付
     * */
    @PostMapping("/bankCardPayment")
    public AjaxResult bankCardPayment(HttpServletRequest request, @RequestBody FlightPayVo flightPayVo){
        String hotelPay;
        try {
            hotelPay = flightService.bankCardPayment(flightPayVo, request);
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(hotelPay);
    }

    /**
     * 改签机票银行卡支付
     * @param flightPayVo
     * @return
     */
    @PostMapping("/changeBankCardPay")
    public AjaxResult changeBankCardPay(HttpServletRequest request, @RequestBody FlightPayVo flightPayVo) {
        String cardPay;
        try {
            cardPay = flightService.changeBankCardPay(flightPayVo, request);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(cardPay);
    }

    //清理机票redis缓存
    @PostMapping("/clearFlightCache")
    public AjaxResult clearFlightCache(@RequestBody Map<String, String> map)
    {
        String depDate = map.get("depDate");
        String dstAirport = map.get("dstAirport");
        String orgAirport = map.get("orgAirport");
        String backDepDate = map.get("backDepDate");
        boolean result = flightService.clearFlightCache(depDate, dstAirport, orgAirport, backDepDate);
        if (result)
        {
            return AjaxResult.success("清理缓存成功！");
        }
        return AjaxResult.error("缓存无需清理！");
    }
}
